using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using ThridGroup.ERP.WarehouseManagement;
using ThridGroup.ERP.DTO;

namespace ThridGroup.ERP.Web.Areas.WarehouseManagement.Controllers
{
    [Area("WarehouseManagement")]
    [Route("WarehouseManagement/[controller]")]
    public class WarehouseSettingController : AbpController
    {
        private readonly IWarehouseSettingService _warehouseSettingService;
        private readonly ILogger<WarehouseSettingController> _logger;

        public WarehouseSettingController(
            IWarehouseSettingService warehouseSettingService,
            ILogger<WarehouseSettingController> logger)
        {
            _warehouseSettingService = warehouseSettingService;
            _logger = logger;
        }

        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            _logger.LogInformation("访问仓库设置管理页面");
            return View();
        }

        [HttpGet]
        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id.HasValue)
            {
                var model = await _warehouseSettingService.GetWarehouseSetting(id.Value);
                return View(model);
            }
            
            return View(new WarehouseSettingDto());
        }

        [HttpGet]
        [Route("GetWarehouseSettings")]
        public async Task<IActionResult> GetWarehouseSettings(string depotCode = null, string depotName = null, string location = null, int page = 1, int limit = 10)
        {
            try
            {
                _logger.LogInformation($"开始获取仓库设置列表, 页码: {page}, 每页数量: {limit}, 筛选条件: depotCode={depotCode}, depotName={depotName}, location={location}");
                
                // 从服务层获取分页数据
                var (data, total) = await _warehouseSettingService.GetWarehouseSettingsPaged(depotCode, depotName, location, page, limit);
                
                _logger.LogInformation($"获取仓库设置列表成功，总数：{total}, 当前页数据：{data?.Count ?? 0}条");
                
                return Json(new { code = 0, msg = "获取成功", count = total, data = data });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仓库设置列表失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<WarehouseSettingDto>() });
            }
        }

        [HttpGet]
        [Route("Get/{id}")]
        public async Task<IActionResult> GetWarehouseSetting(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取仓库设置，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的仓库设置ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                var model = await _warehouseSettingService.GetWarehouseSetting(id);
                if (model == null)
                {
                    _logger.LogWarning($"未找到指定的仓库设置，ID：{id}");
                    return Json(new { code = 1, msg = "未找到指定的仓库设置" });
                }

                _logger.LogInformation($"成功获取仓库设置，ID：{id}");
                return Json(new { code = 0, msg = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取仓库设置失败，ID：{id}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        [HttpGet]
        [Route("GetById/{id}")]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取仓库设置通过GetByIdAsync，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的仓库设置ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                var model = await _warehouseSettingService.GetByIdAsync(id);
                if (model == null)
                {
                    _logger.LogWarning($"未找到指定的仓库设置，ID：{id}");
                    return Json(new { code = 1, msg = "未找到指定的仓库设置" });
                }

                _logger.LogInformation($"成功获取仓库设置，ID：{id}");
                return Json(new { code = 0, msg = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取仓库设置失败，ID：{id}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Add")]
        public async Task<IActionResult> AddWarehouseSetting([FromBody] WarehouseSettingDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始添加仓库设置，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("添加仓库设置时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                // 验证字段
                if (string.IsNullOrWhiteSpace(dto.DepotCode))
                {
                    _logger.LogWarning("添加仓库设置时编码为空");
                    return Json(new { code = 1, msg = "仓库编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.DepotName))
                {
                    _logger.LogWarning("添加仓库设置时名称为空");
                    return Json(new { code = 1, msg = "仓库名称不能为空" });
                }

                _logger.LogInformation("准备调用服务层添加仓库设置");
                
                var id = await _warehouseSettingService.AddWarehouseSetting(dto);
                _logger.LogInformation($"成功添加仓库设置，ID：{id}");
                return Json(new { code = 0, msg = "添加成功", data = id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加仓库设置失败：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> UpdateWarehouseSetting([FromBody] WarehouseSettingDto dto)
        {
            try
            {
                _logger.LogInformation($"开始更新仓库设置：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                
                if (dto == null)
                {
                    _logger.LogWarning("更新仓库设置时提交的数据为空");
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (dto.Id <= 0)
                {
                    _logger.LogWarning($"更新仓库设置时ID无效：{dto.Id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                if (string.IsNullOrWhiteSpace(dto.DepotCode))
                {
                    _logger.LogWarning("更新仓库设置时编码为空");
                    return Json(new { code = 1, msg = "仓库编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.DepotName))
                {
                    _logger.LogWarning("更新仓库设置时名称为空");
                    return Json(new { code = 1, msg = "仓库名称不能为空" });
                }

                _logger.LogInformation("准备调用服务层更新仓库设置");
                var id = await _warehouseSettingService.UpdateWarehouseSetting(dto);
                _logger.LogInformation($"成功更新仓库设置，ID：{id}");
                return Json(new { code = 0, msg = "更新成功", data = id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新仓库设置失败：{System.Text.Json.JsonSerializer.Serialize(dto)}");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> DeleteWarehouseSetting(int id)
        {
            try
            {
                _logger.LogInformation($"开始删除仓库设置，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的仓库设置ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                await _warehouseSettingService.DeleteWarehouseSetting(id);
                _logger.LogInformation($"成功删除仓库设置，ID：{id}");
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除仓库设置失败，ID：{id}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }
    }
} 